package page

import (
	"time"

	"BookStack/pkg/errors"
	"BookStack/pkg/utils"
)

// 页面状态常量
const (
	StatusDraft     int = 0 // 草稿
	StatusPublished int = 1 // 已发布
)

// Page 自定义页面实体
type Page struct {
	ID          uint       `json:"id" gorm:"primaryKey;column:id"`
	Title       string     `json:"title" gorm:"column:title;size:100;not null"`
	Slug        string     `json:"slug" gorm:"column:slug;size:100;uniqueIndex;not null"`
	Content     string     `json:"content" gorm:"column:content;type:text"`
	Description string     `json:"description" gorm:"column:description;size:200"`
	Status      int        `json:"status" gorm:"column:status;default:0;comment:0草稿,1已发布"`
	ViewCount   int64      `json:"view_count" gorm:"column:view_count;default:0"`
	CreatedBy   uint       `json:"created_by" gorm:"column:created_by;not null"`
	UpdatedBy   uint       `json:"updated_by" gorm:"column:updated_by"`
	DeletedBy   uint       `json:"deleted_by" gorm:"column:deleted_by"`
	CreatedAt   time.Time  `json:"created_at" gorm:"column:created_at;autoCreateTime"`
	UpdatedAt   time.Time  `json:"updated_at" gorm:"column:updated_at;autoUpdateTime"`
	DeletedAt   *time.Time `json:"deleted_at" gorm:"column:deleted_at;index"`
}

// TableName 指定表名
func (Page) TableName() string {
	return "pages"
}

// NewPage 创建一个新的自定义页面
func NewPage(title, slug, content, description string, status int, createdBy uint) *Page {
	if title == "" {
		return nil
	}
	if slug == "" {
		return nil
	}

	now := utils.TimeToJSONTime(time.Now()).Time()
	return &Page{
		Title:       title,
		Slug:        slug,
		Content:     content,
		Description: description,
		Status:      status,
		CreatedBy:   createdBy,
		UpdatedBy:   createdBy,
		ViewCount:   0,
		CreatedAt:   now,
		UpdatedAt:   now,
	}
}

// UpdateContent 更新页面内容
func (p *Page) UpdateContent(title, slug, content, description string) error {
	if title == "" {
		return errors.New(errors.ErrCodePageTitleRequired, "")
	}

	p.Title = title
	p.Slug = slug
	p.Content = content
	p.Description = description
	p.UpdatedAt = utils.TimeToJSONTime(time.Now()).Time()
	return nil
}

// UpdateStatus 更新页面状态
func (p *Page) UpdateStatus(status int) error {
	if status < StatusDraft || status > StatusPublished {
		return errors.New(errors.ErrCodePageStatusInvalid, "")
	}

	p.Status = status
	p.UpdatedAt = utils.TimeToJSONTime(time.Now()).Time()
	return nil
}

// IsPublished 检查页面是否已发布
func (p *Page) IsPublished() bool {
	return p.Status == StatusPublished
}

// IncrementViewCount 增加阅读计数
func (p *Page) IncrementViewCount() {
	p.ViewCount++
	p.UpdatedAt = utils.TimeToJSONTime(time.Now()).Time()
}
